<template>
  <div class="box">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator="/" class="user-tou">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        style="margin-bottom: 10px"
      />
      <!--steps 步骤条 -->
      <el-steps
        finish-status="success"
        :space="200"
        align-center
        :active="activeIndex - 0"
      >
        <!-- active为0设置当前激活步骤 步骤条只能绑定数字型我们需要转化-0变数字-->
        <el-step title="基本信息" />
        <el-step title="商品参数" />
        <el-step title="商品属性" />
        <el-step title="商品图片" />
        <el-step title="商品内容" />
        <el-step title="完成" />
      </el-steps>
      <!--1. tabs标签页 -->
      <!-- tabPosition="left|right|top|bottom" 控制方向 -->
      <!-- 2. 步骤条与tabs标签页的联动效果 tabs使用v-mode指定激活哪个面板
      如果点击第一个，就会把第一个的name保存到activeName身上-->
      <!-- type为card选项卡变成标签风格 -->
      <el-form
        ref="appformref"
        :model="appform"
        :rules="appformrules"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="appbefore"
          @tab-click="apptabclicked"
        >
          <!-- 商品参数点击事件@tab-click="appclicked" -->
          <!-- before-leave 判断切换标签页是不是当前页签有两个参数一个是当前页，有一个是要去的页签 同时判断当前页签三级分类是不是选中三个选项不是不允许切换  -->
          <!-- 基本信息面板 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="appform.goods_name" />
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="appform.goods_price" type="number" />
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="appform.goods_weight" type="number" />
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="appform.goods_number" type="number" />
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="appform.goods_cat"
                :options="applist"
                :props="appprops"
                @change="appchange"
              />
              <!-- 级联选择器 -->
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的item项 -->
            <el-form-item
              v-for="item in manytabapp"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  :label="cb"
                  border
                />
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlytabapp"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="appupload"
              :on-preview="apphandle"
              :on-remove="appremove"
              list-type="picture"
              :headers="headerobj"
            >
              <!-- action图片上传的后台api地址 -->
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4" style="height: 400px">
            <quill-editor
              style="height: 200px"
              v-model="appform.goods_introduce"
            >
            </quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="btnAdd" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// require styles
// require styles
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";

import { apphuo, apphuocan, apphuotian } from "@/api/goods";
import _ from "lodash";
export default {
  name: "LoginIndex",
  components: {
    quillEditor,
  },
  data() {
    return {
      // name是字符串类型，所以要将activeIndex变为字符串0
      // 添加商品表单数据对象
      activeIndex: "0",
      appform: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        goods_introduce: "",
        attrs: [],
      },
      // goods_cat:[] 存放分类的id

      // 添加商品表单验证规则对象
      appformrules: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
          },
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: "blur",
          },
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品数量",
            trigger: "blur",
          },
        ],
        goods_cat: [
          {
            required: true,
            message: "请输入商品分类",
            trigger: "blur",
          },
        ],
      },
      // 商品分类数据
      applist: [],
      // 级联选择器的配置项
      appprops: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      // 动态参数列表数据
      manytabapp: [],
      // 静态参数列表数据
      onlytabapp: [],
      // 上传图片url地址
      appupload: "https://www.liulongbin.top:8888/api/private/v1",
      headerobj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
    };
  },

  computed: {
    // 三级分类id
    catapp() {
      if (this.appform.goods_cat.length === 3) {
        // console.log(this.appform.goods_cat);
        // console.log(this.appform.goods_cat.length);
        return this.appform.goods_cat[2];
      }
      return null;
    },
  },
  created() {
    this.getapplist();
  },
  methods: {
    // 获取所有商品分类数据
    async getapplist() {
      const res = await apphuo();
      console.log(res);
      this.applist = res.data;
    },
    // 点击级联选择器会触发
    appchange() {
      // console.log(this.appform.goods_cat);
      if (this.appform.goods_cat.length !== 3) {
        // 需求展示选择到三级，没有到三级我们清空选项
        this.appform.goods_cat = [];
      }
    },
    // 标签页离开触发这个函数
    appbefore(appold, appxin) {
      if (appxin === "0" && this.appform.goods_cat.length !== 3) {
        // 判断去的页签是当前页0和三级分类也没有选到3级  不跳转
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    // 选中tab触发
    async apptabclicked() {
      // 证明访问的是动态参数面板
      if (this.activeIndex === "1") {
        const res = await apphuocan(this.catapp, {
          sel: "many",
        });
        // console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("获取动态参数列表失败");
        }
        // 将数组渲染成复选框，但是attr_vals是字符串，首先我们应该先把attr_vals字符串转变为数组
        // 先判断是否为空字符串，然后将它使用split（‘ ’）变成数组

        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
          this.manytabapp = res.data;
        });

        // console.log(this.manytabapp);
      } else if (this.activeIndex === "2") {
        const res = await apphuocan(this.catapp, {
          sel: "only",
        });
        if (res.meta.status !== 200) {
          return this.$message.error("获取静态参数列表失败");
        }
        this.onlytabapp = res.data;
      }
    },
    // 处理图片预览效果
    apphandle() {},
    // 处理移除图片操作
    appremove() {},
    //添加商品
    add() {
      this.$refs.appformref.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写必要的表单项！");
        }
        //执行添加业务办理
        const form = _.cloneDeep(this.appform);
        // console.log(form);
        form.goods_cat = form.goods_cat.join(",");
        //处理动态参数
        this.manytabapp.forEach((item) => {
          const newinfo = {
            cat_id: item.cat_id,
            cat_value: item.attr_vals.join(""),
          };
          this.appform.attrs.push(newinfo);
        });
        //处理静态参数
        this.onlytabapp.forEach((item) => {
          const newinfo = { attr_id: item.attr_id, attr_value: item.attr_vals };
          this.appform.attrs.push(newinfo);
        });
        form.attrs = this.appform.attrs;
        console.log(form);
        //发起请求添加商品
        //商品名称必须是唯一的
        const res = await apphuotian(form);
        // console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("添加商品失败！");
        }
        this.$message.success("添加商品成功！");
        this.$router.push("/goods");
      });
    },
  },
};
</script>

<style lang="less" scoped>
.user-tou {
  margin-bottom: 10px;
}
.el-steps {
  margin: 15px 0;
}
.el-step {
  font-size: 13px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.btnAdd {
  margin-top: 80px;
}
</style>
